package com.itcast.mallweb.service.impl;


import com.itcast.admin.dto.CommodityDTO;
import com.itcast.admin.dto.CommondityAmendDTO;
import com.itcast.admin.entity.*;
import com.itcast.admin.vo.DityVO;
import com.itcast.constant.MessageConstant;
import com.itcast.exception.BaseException;
import com.itcast.mallweb.mapper.CommodityMapper;
import com.itcast.mallweb.service.CommodityService;
import com.itcast.result.Result;
import com.itcast.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

@Service
@Slf4j
public class CommodityServiceImpl implements CommodityService {
    @Autowired
    private CommodityMapper commodityMapper;
    @Autowired
    private AliOssUtil aliOssUtil;

    //新增商品
    @Transactional
    public Result<String> dityAdd(CommodityDTO commodityDTO, MultipartFile[] files) {
        Commodity commodity = new Commodity();
        commodity = commodity.builder()
                .discount(9.9)
                .status(1)
                .createTime(LocalDateTime.now())
                .build();
        BeanUtils.copyProperties(commodityDTO, commodity);

        commodityMapper.dityAdd(commodity);
        List<String> urls = new ArrayList<>();
        //图片路径存储
        for (MultipartFile file : files) {
            try {
                //原始文件名
                String originalFilename = file.getOriginalFilename();
                //截取原始文件名的后缀 37-57cj.png
                String extension = originalFilename.substring(originalFilename.lastIndexOf("."));//截取最后一个点的后半部分
                //构建新文件名称
                String objectName = UUID.randomUUID().toString() + extension;
                //文件的请求路径
                String upload = aliOssUtil.upload(file.getBytes(), objectName); //把这个返回给前端
                urls.add(upload);
            } catch (IOException e) {
                log.error("文件上传失败：{}", e);
            }
        }

        //生成一个实体图片存储
        List<DityUrl> dityUrls = new ArrayList<>();
        for (String url : urls) {
            DityUrl build = DityUrl.builder()
                    .dityId(commodity.getId())
                    .avatar(url)
                    .build();

            dityUrls.add(build);
        }
        //前面运行完毕之后新增商品
        commodityMapper.dityUrl(dityUrls);
        return Result.success();
    }

    //查询单个商品
    public DityVO dityQuery(Integer id) {
        DityVO dityVO = commodityMapper.dityQuery(id);
        return dityVO;
    }

    //查询全部商品
    public List<com.itcast.applet.entity.Commodity> dityAllQuery() {
        List<com.itcast.applet.entity.Commodity> commodityList = commodityMapper.dityAllQuery();
        return commodityList;
    }

    //批量删除商品
    @Transactional
    public void dityDetele(List<Integer> ids) {
        //删除商品
        commodityMapper.dityDetele(ids);
        //删除商品图片
        commodityMapper.dityUrlDetele(ids);
    }

    //修改商品
    @Transactional
    public void dityAmend(CommondityAmendDTO commondityAmendDTO) {
        //拿到删除图片的集合先删除图片 - 解析成数字
        String ids = commondityAmendDTO.getIds();
        if(ids != null && !ids.equals("")) {
            String[] parts = ids.split(",");
            List<Integer> idsList = new ArrayList<>();
            for (String part : parts) {
                int number = Integer.parseInt(part.trim()); // `trim()` to remove any surrounding spaces
                idsList.add(number);
            }
            commodityMapper.dityUrlAmendDetele(idsList);
        }

        List<String> avatar = commondityAmendDTO.getAvatar();
        //有新文件传来直接新增
        if(avatar != null && avatar.size() > 0){
            List<DityUrl> dityUrls = new ArrayList<>();
            for (String s : avatar) {
                DityUrl dityUrl = DityUrl.builder()
                        .dityId(commondityAmendDTO.getId())
                        .avatar(s)
                        .build();
                dityUrls.add(dityUrl);
            }
            //新增图片
            commodityMapper.dityUrl(dityUrls);
        }
        //最后修改商品信息
        Commodity commodity = new Commodity();
        BeanUtils.copyProperties(commondityAmendDTO, commodity);
        commodityMapper.dityAmend(commodity);
    }


}